package com.wwtech.epp.ui.activity.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseFragment;
import com.wwtech.epp.base.SealAppContext;
import com.wwtech.epp.base.SealUserInfoManager;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.db.Friend;
import com.wwtech.epp.entity.CreateGroup;
import com.wwtech.epp.entity.eventbus.ModifyGroupInfo;
import com.wwtech.epp.service.broadcast.BroadcastManager;
import com.wwtech.epp.service.pinyin.CharacterParser;
import com.wwtech.epp.service.pinyin.PinyinComparator;
import com.wwtech.epp.ui.activity.friend.AddPersonActivity;
import com.wwtech.epp.ui.activity.friend.UserDetailActivity;
import com.wwtech.epp.ui.activity.main.component.DaggerContactComponent;
import com.wwtech.epp.ui.activity.main.contract.ContactContract;
import com.wwtech.epp.ui.activity.main.module.ContactModule;
import com.wwtech.epp.ui.activity.main.presenter.ContactPresenter;
import com.wwtech.epp.ui.activity.mine.MyInfoActivity;
import com.wwtech.epp.ui.adapter.main.ContactAdapter;
import com.wwtech.epp.ui.adapter.main.FriendListAdapter;
import com.wwtech.epp.utils.UIUtils;
import com.wwtech.epp.view.ContactMorePopWindow;
import com.wwtech.epp.view.SelectableRoundedImageView;
import com.wwtech.epp.view.SideBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.main
 * @Description: $description 用户的好友界面，需要获取用户的所有的好友关系，包括好友，组织架构，还有群组。当这些信息都全部拉取完毕，再显示出来
 * @date 2017/08/21 11:13:55
 */

public class ContactFragment extends BaseFragment implements ContactContract.View, View.OnClickListener, ContactMorePopWindow.OnItemClickListener
{

    @Inject
    ContactPresenter mPresenter;
    @Inject
    ContactAdapter contactAdapter;
    @BindView(R.id.search)
    EditText search;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.group_dialog)
    TextView groupDialog;
    @BindView(R.id.sidrbar)
    SideBar sidrbar;
    @BindView(R.id.show_no_friend)
    TextView showNoFriend;

    public static String URL_FREIND = "";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.seal_more)
    ImageView sealMore;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.layout_top)
    LinearLayout layoutTop;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private View mHeadView;
    private TextView mUnreadTextView;
    private SelectableRoundedImageView mSelectableRoundedImageView;
    private TextView mNameTextView;
    private List<Friend> mFriendList;
    private List<Friend> mFilteredFriendList;
    private String mId;
    private String mCacheName;
    private FriendListAdapter mFriendListAdapter;

    private PinyinComparator mPinyinComparator;
    private String groupName = "";

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser mCharacterParser;

    private List<Friend> friendsList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact, null);
        ButterKnife.bind(this, view);
        Bundle mBundle = getArguments();
        initView(view);
        initData();
        updateUI();
        refreshUIListener();
        sealMore.setVisibility(View.VISIBLE);
        return view;
    }

    private void initView(View view) {
        sidrbar.setTextView(groupDialog);
        LayoutInflater mLayoutInflater = LayoutInflater.from(getActivity());
        mHeadView = mLayoutInflater.inflate(R.layout.item_contact_list_header, null);
        mUnreadTextView = (TextView) mHeadView.findViewById(R.id.tv_unread);
        RelativeLayout newFriendsLayout = (RelativeLayout) mHeadView.findViewById(R.id.re_newfriends);
        RelativeLayout groupLayout = (RelativeLayout) mHeadView.findViewById(R.id.re_chatroom);
        RelativeLayout publicServiceLayout = (RelativeLayout) mHeadView.findViewById(R.id.publicservice);
        RelativeLayout selfLayout = (RelativeLayout) mHeadView.findViewById(R.id.contact_me_item);
        mSelectableRoundedImageView = (SelectableRoundedImageView) mHeadView.findViewById(R.id.contact_me_img);
        mNameTextView = (TextView) mHeadView.findViewById(R.id.contact_me_name);
        updatePersonalUI();
        listview.addHeaderView(mHeadView);
        showNoFriend.setVisibility(View.VISIBLE);

        selfLayout.setOnClickListener(this);
        groupLayout.setOnClickListener(this);
        newFriendsLayout.setOnClickListener(this);
        publicServiceLayout.setOnClickListener(this);
        //设置右侧触摸监听
        sidrbar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = mFriendListAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    listview.setSelection(position);
                }

            }
        });
        layoutTop.setPadding(0, (int) (UIUtils.getStatusBarHeight(getActivity()) * 0.8), 0, 0);
        tvTitle.setText("通讯录");
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        contactAdapter.expandAll();
        recyclerView.setAdapter(contactAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddFriendSuceess(String content) {
        KLog.i("收到eventbus消息" + content);
        mPresenter.initList();
        updateUI();
//        if (content.equals("success")) {
//            Map<String, String> map = new HashMap<>();
//            map.put("pageSize", "50");
//            map.put("pageNum", "1");
//            mPresenter.getFriends(map);
//        }
    }


    private void initData() {
        mFriendList = new ArrayList<>();
        FriendListAdapter adapter = new FriendListAdapter(getActivity(), mFriendList);
        listview.setAdapter(adapter);
        mFilteredFriendList = new ArrayList<>();
        //实例化汉字转拼音类
        mCharacterParser = CharacterParser.getInstance();
        mPinyinComparator = PinyinComparator.getInstance();
        //OpFriend();
    }

    private void OpFriend() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
        map.put("targetId", "10015");
        map.put("op", "0");         //0添加,1删除
        mPresenter.opFriend(map);
    }

    private void updateUI() {
        mPresenter.initList();
        Map<String, String> map = new HashMap<>();
        map.put("pageSize", "50");
        map.put("pageNum", "1");
        mPresenter.getFriends(map);

        Map<String, String> map1 = new HashMap<>();
        mPresenter.getAllNode(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("pageSize", "50");
        map2.put("pageNum", "1");
        mPresenter.getGroup(map2, ContainValue.userLogin.getData().getUserId() + "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onModifyGroupSuccess(ModifyGroupInfo modifyGroupInfo) {
        KLog.i("收到消息le ");
        updateUI();
        refreshUIListener();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setFriends(List<Friend> friends) {
        KLog.i("设置好友信息....." + friends.size());
        for (Friend freind : friends) {

            /**
             * 刷新用户缓存数据。
             *
             * @param userInfo 需要更新的用户缓存数据。
             */
//            RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
//                @Override
//                public UserInfo getUserInfo(String userId) {
//                    KLog.i("设置好友信息.....");
//                    return findUserById(freind);//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
//                }
//
//            }, true);
            RongIM.getInstance().refreshUserInfoCache(findUserById(freind));
        }
        updateFriendsList(friendsList);
    }

    @Override
    public void onNodeBack(List<MultiItemEntity> list) {
        contactAdapter.setNewData(list);
    }

    @Override
    public void onCreateGroupSuccess(CreateGroup createGroup) {
        updateUI();
        RongIM.getInstance().startGroupChat(getActivity(), createGroup.getData().getGroupId(), groupName);
    }

    private UserInfo findUserById(Friend friend) {
        Friend friend1 = new Friend(friend.getPhone(), friend.getUserId() + "", friend.getNickname(), Uri.parse(friend.getAvatar()));
        friendsList.add(friend1);
        return new UserInfo(friend.getUserId() + "", friend.getNickname(), Uri.parse(friend.getAvatar()));
    }

    private void updateFriendsList(List<Friend> friendsList) {
        //updateUI fragment初始化和好友信息更新时都会调用,isReloadList表示是否是好友更新时调用
        KLog.i("更新好友列表");
        boolean isReloadList = false;
        if (mFriendList != null && mFriendList.size() > 0) {
            mFriendList.clear();
            isReloadList = true;
        }
        mFriendList = friendsList;
        if (mFriendList != null && mFriendList.size() > 0) {
            handleFriendDataForSort();
            showNoFriend.setVisibility(View.GONE);
        } else {
            KLog.i("好友为空");
            showNoFriend.setVisibility(View.VISIBLE);
            return;
        }


        // 根据a-z进行排序源数据
        Collections.sort(mFriendList, mPinyinComparator);
        if (isReloadList) {
            sidrbar.setVisibility(View.VISIBLE);
            mFriendListAdapter.updateListView(mFriendList);
        } else {
            sidrbar.setVisibility(View.VISIBLE);
            mFriendListAdapter = new FriendListAdapter(getActivity(), mFriendList);

            listview.setAdapter(mFriendListAdapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (listview.getHeaderViewsCount() > 0) {
                        startFriendDetailsPage(mFriendList.get(position - 1));
                    } else {
                        startFriendDetailsPage(mFilteredFriendList.get(position));
                    }
                }
            });


            listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                    Friend bean = mFriendList.get(position - 1);
                    startFriendDetailsPage(bean);
                    return true;
                }
            });
            search.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                    filterData(s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() != 0) {
                        if (listview.getHeaderViewsCount() > 0) {
                            listview.removeHeaderView(mHeadView);
                        }
                    } else {
                        if (listview.getHeaderViewsCount() == 0) {
                            listview.addHeaderView(mHeadView);
                        }
                    }
                }
            });
            mFriendListAdapter.notifyDataSetChanged();
        }
    }

    private void handleFriendDataForSort() {
        for (Friend friend : mFriendList) {
            if (friend.isExitsDisplayName()) {
                String letters = replaceFirstCharacterWithUppercase(friend.getDisplayNameSpelling());
                friend.setLetters(letters);
            } else {
                String letters = replaceFirstCharacterWithUppercase(friend.getNameSpelling());
                friend.setLetters(letters);
            }
        }
    }

    private String replaceFirstCharacterWithUppercase(String spelling) {
        if (!TextUtils.isEmpty(spelling)) {
            char first = spelling.charAt(0);
            char newFirst = first;
            if (first >= 'a' && first <= 'z') {
                newFirst -= 32;
            }
            return spelling.replaceFirst(String.valueOf(first), String.valueOf(newFirst));
        } else {
            return "#";
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr 需要过滤的 String
     */
    private void filterData(String filterStr) {
        List<Friend> filterDateList = new ArrayList<>();

        try {
            if (TextUtils.isEmpty(filterStr)) {
                filterDateList = mFriendList;
            } else {
                filterDateList.clear();
                for (Friend friendModel : mFriendList) {
                    String name = friendModel.getName();
                    String displayName = friendModel.getDisplayName();
                    if (!TextUtils.isEmpty(displayName)) {
                        if (name.contains(filterStr) || mCharacterParser.getSpelling(name).startsWith(filterStr) || displayName.contains(filterStr) || mCharacterParser.getSpelling(displayName).startsWith(filterStr)) {
                            filterDateList.add(friendModel);
                        }
                    } else {
                        if (name.contains(filterStr) || mCharacterParser.getSpelling(name).startsWith(filterStr)) {
                            filterDateList.add(friendModel);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, mPinyinComparator);
        mFilteredFriendList = filterDateList;
        mFriendListAdapter.updateListView(filterDateList);
    }

    private void startFriendDetailsPage(Friend friend) {
        Intent intent = new Intent(getActivity(), UserDetailActivity.class);
//        intent.putExtra("type", CLICK_CONTACT_FRAGMENT_FRIEND);
        intent.putExtra("friend", friend);
        startActivity(intent);
    }

    private void updatePersonalUI() {
        SharedPreferences sp = AppConfig.getInstance().getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        mId = sp.getString(ContainValue.LOGIN_ID, "");
        mCacheName = sp.getString(ContainValue.LOGIN_NAME, "");
        final String header = sp.getString(ContainValue.LOGING_PORTRAIT, "");
        mNameTextView.setText(mCacheName);
        if (!TextUtils.isEmpty(mId)) {
            UserInfo userInfo = new UserInfo(mId, mCacheName, Uri.parse(header));
            String portraitUri = SealUserInfoManager.getInstance().getPortraitUri(userInfo);
            ImageLoader.getInstance().displayImage(portraitUri, mSelectableRoundedImageView, AppConfig.getOptions());
        }
    }

    private void refreshUIListener() {
        BroadcastManager.getInstance(getActivity()).addAction(SealAppContext.UPDATE_FRIEND, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String command = intent.getAction();
                if (!TextUtils.isEmpty(command)) {
                    updateUI();
                }
            }
        });

        BroadcastManager.getInstance(getActivity()).addAction(SealAppContext.UPDATE_RED_DOT, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String command = intent.getAction();
                if (!TextUtils.isEmpty(command)) {
                    mUnreadTextView.setVisibility(View.INVISIBLE);
                }
            }
        });
        BroadcastManager.getInstance(getActivity()).addAction(ContainValue.CHANGEINFO, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updatePersonalUI();
            }
        });
    }


    @Override
    protected void setupFragmentComponent() {
        DaggerContactComponent
                .builder()
                .appComponent(((AppConfig) getActivity().getApplication()).getApplicationComponent())
                .contactModule(new ContactModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(ContactContract.ContactContractPresenter presenter) {
        mPresenter = (ContactPresenter) presenter;
    }

    @Override
    protected void initDataFromLocal() {

    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.seal_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.seal_more:
                if (ContainValue.partPerson != null) {
                    ContainValue.partPerson.clear();
                }
                ContactMorePopWindow morePopWindow = new ContactMorePopWindow(getActivity());
                morePopWindow.showPopupWindow(sealMore);
                morePopWindow.setOnItemClickListener(this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != 20) {
            ContainValue.partPerson = null;
            return;
        }
        if (ContainValue.partPerson != null && ContainValue.partPerson.size() != 0 && ContainValue.partPerson.size() != 1) {
            String name = ContainValue.userLogin.getData().getNickName() + ",";
            String members = ContainValue.userLogin.getData().getUserId() + ",";
            for (int i = 0; i < ContainValue.partPerson.size(); i++) {
                name += ContainValue.partPerson.get(i).getNickname() + ",";
                members += ContainValue.partPerson.get(i).getUserId() + ",";
                if (i >= 2) {
                    break;
                }
            }

            name = name.substring(0, name.length() - 1) + "的群聊";
            KLog.i(name);
            KLog.i(members.substring(0, members.length() - 1));
            Map<String, RequestBody> map = new HashMap<>();
            MediaType textType = MediaType.parse("text/plain");
            map.put("ownerUid", RequestBody.create(textType, ContainValue.userLogin.getData().getUserId() + ""));
            map.put("groupName", RequestBody.create(textType, name));
            map.put("groupDesc", RequestBody.create(textType, name));
            groupName = name;
            map.put("members", RequestBody.create(textType, members.substring(0, members.length() - 1)));

            mPresenter.createGroup(map);
        }
        if (ContainValue.partPerson != null && ContainValue.partPerson.size() == 1) {
            if (("" + ContainValue.userLogin.getData().getUserId()).equals(ContainValue.partPerson.get(0).getUserId())) {
                Intent intent = new Intent(getActivity(), MyInfoActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(getActivity(), UserDetailActivity.class);
                intent.putExtra("friend", ContainValue.partPerson.get(0));
                startActivity(intent);
            }
        }
    }

    @Override
    public void onCreatGroup() {
        if (ContainValue.partPerson == null) {
            ContainValue.partPerson = new ArrayList<>();
        }
        Intent intent = new Intent(getActivity(), AddPersonActivity.class);
        intent.putExtra("title", "发起群聊");
        Friend friend = new Friend(ContainValue.userLogin.getData().getUserId() + "", ContainValue.userLogin.getData().getNickName(), Uri.parse(ContainValue.userLogin.getData().getAvatar()));
        friend.setUserId(ContainValue.userLogin.getData().getUserId() + "");
        ContainValue.partPerson.add(friend);
        startActivityForResult(intent, 0);
    }

}